<!--
 * @Author: wuheng wuheng@szhbzc.com
 * @Date: 2024-12-24 17:35:14
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-02-25 20:28:39
 * @FilePath: \web-appc:\Users\wuheng\Desktop\WugangNew\src\views\dishmana\dishaccounting\components\bominfo.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="detailTable">
    <el-table :data="dishbominfoData" max-height="500" show-summary :summary-method="getSummaries">
      <el-table-column type="index" label="序号" width="120" />
      <el-table-column prop="ingredientsTypeName" label="配料分组" width="180" />
      <el-table-column prop="spuCommonlyName" label="SPU名称" />
      <el-table-column prop="skuName" label="SKU名称">
        <template #default="scope">
          <div class="spuboxlink">
            <pb-select v-model="scope.row.skuCode" width="100" placeholder="请选择指定SKU" keys="skuCode" label="skuName"
              :options="scope.row.spuMatchedSkuVOList ? scope.row.spuMatchedSkuVOList : []"
              @change="setWeiRecoveFn($event, scope.row)" />

            <el-popover placement="right" trigger="hover" content="选择匹配SKU">
              <template #reference>
                <pb-icon name="spulink" class="ml-2 link" @click="openMatch(scope.row)"></pb-icon>
              </template>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="推荐SKU">
        <template #default="{ row }">
          <div>
            <el-switch v-model="row.isPurchasing" :active-value="1" :inactive-value="0" class="ml-2"
              @change="switchchange($event, row)" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="weight" label="配量(g/份)" :align="'right'" />
      <el-table-column prop="recoveryRate" label="出成率(%)" :align="'right'" />
      <el-table-column prop="price" label="单价(kg/元)" :align="'right'" />
      <el-table-column prop="cost" label="成本(元)" :align="'right'">
        <template #header>
          <div class="flex items-center" style="justify-content: right;">
            <span class="m-r2">成本(元)</span>
            <el-popover placement="top" width="260" trigger="hover" content="（配量*单价）/（出成率(%)*1000）">
              <template #reference>
                <pb-icon name="question" size="20"></pb-icon>
              </template>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <MatchSku ref="matchPopRef" @refresh="getBomlistfn"></MatchSku>
  </div>
</template>

<script lang="ts" setup>
import { getSkuInfoList } from '@/api/Sku'
import { GetBomdishPageListApi } from '@/api/Dashmana'
import MatchSku from './matchSku.vue'
const props = defineProps({
  Bomdata: {
    type: Object,
    default: {}
  }
})
// const filterMethod = (query) => {
//   // console.log(query, '22')
//   // 注意：这里应该使用 query 而不是 val，因为 val 是你函数内部的参数名，
//   // 但通常我们会使用 query 来表示用户输入的搜索词。
//   if (query) {
//     DishListData.SpuInfoListList = DishListData.oldSpuInfoListList.filter((item) => {
//       return item.spuName?.toLowerCase().includes(query.toLowerCase()) || item.mnemonicCode?.toLowerCase().includes(query.toLowerCase())
//     })
//   } else {
//     DishListData.SpuInfoListList = DishListData.oldSpuInfoListList
//   }
// };
const setWeiRecoveFn = (val: any, row: any) => {
  // console.log(val, '22', row)
  row.price = val[0].kilogramPrice
  row.recoveryRate = val[0].recoveryRate
  console.log((row.weight * row.price) / (row.recoveryRate * 1000), row.weight, row.price, row.recoveryRate * 1000)
  // （配重 * 单价）/（出成率*1000）
  if (isFinite(row.weight) && isFinite(row.price)) {
    row.cost = parseFloat(((row.weight * row.price) / (row.recoveryRate / 100 * 1000)).toFixed(2));
  } else {
    // 如果不是有效数字，将 cost 设置为 0 或其他默认值
    row.cost = 0;
  }
}
const matchPopRef = ref(null as any)
const openMatch = (row: any) => {
  // let { spuCode, spuName } = { ...row }
  let spuCode = row.spuCode
  let spuName = row.spuCommonlyName
  matchPopRef.value.showFn({ spuCode, spuName })
}
const getSummaries = ({ columns, data }: any) => {
  const sums = [] as any;
  columns.forEach((column: any, index: any) => {
    if (index === 0) {
      // 第一列是ID，不显示总计
      sums[index] = '总计';
      return;
    }
    // console.log('1', column.property)
    if (column.property === 'weight' || column.property === 'cost') {
      // console.log('2', column.property)
      // 只为amount1和amount2计算总计
      const values = data.map(item => Number(item[column.property] || 0));
      const sum = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return parseFloat((prev + curr).toFixed(2));;
        } else {
          return prev;
        }
      }, 0);

      sums[index] = sum;
    } else {
      // 其他列不显示总计
      sums[index] = '';
    }
  });

  return sums;
}
const switchchange = (val, row) => {
  // row.isPurchasing = val
}
const getBomlistfn = async () => {
  GetBomdishPageListApi({
    "currentPage": 1,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "dishId": props.Bomdata.dishId
  }).then((res: any) => {
    // console.log(res.data.records)
    dishbominfoData.value = res.data.records
    // getSkulistfn()
  })
}
const dishbominfoData = ref([
])
const getSkulistfn = () => {
  getSkuInfoList({
    currentPage: 1,
    enableState: null,
    matchSpu: null,
    pageSize: -1,
    purchasingCycle: null,
    skuClassCode: "",
    skuCode: "",
    skuName: ""
  }).then((res: any) => {
    let skuCodeList = res.data.records
    const skuMap = new Map();
    const mergedArray = [] as any;
    dishbominfoData.value.forEach((ele: any, indexs) => {
      if (ele.spuCode !== undefined) {
        skuMap.set(ele.spuCode, indexs);
        skuCodeList.forEach(item => {
          if (item.spuCode !== undefined && skuMap.has(item.spuCode)) {
            mergedArray.push(item);
          }
        });
      }
      ele.skuCodeList = mergedArray.lengt > 0 ? mergedArray : skuCodeList
    });

    // return mergedArray;
  })
}
const getdishbominfoDatafn = () => {
  // console.log('我触发了')
  // })
  return dishbominfoData.value
}
onMounted(() => {
  getBomlistfn()
})
defineExpose({ getdishbominfoDatafn });
</script>

<style lang="scss" scoped>
.detailTable {
  ::v-deep thead th {
    background: #F5F5F5 !important;
  }
}

.spuboxlink {
  display: flex;
  align-items: center;

  .link {
    cursor: pointer;
  }
}
</style>
